import { uploadFile } from "./uploadLib";
import axios from "axios";

const contentType = {
  json: "application/json"
};

class RemoteStorage {
  constructor(options = {}) {
    const _defaultConf = {
      domain: window.api.imageDomain,
      tokenUrl: window.api.domain + "/api/sys/files/qiniu/upLoadToken",
      header: {}
    };
    this.conf = Object.assign(_defaultConf, options);
    this.axiosInstance = axios.create({});
  }
  // 设置
  static async setRemoteItem(key, file, token) {
    return await uploadFile(file, token, key);
  }
  // 获取
  async getRemoteItem(key) {
    try {
      const timeStamp = Math.random()
        .toString(36)
        .substring(3, 8);
      return await this.axiosInstance.get(
        `${this.conf.domain}${key}?t=${timeStamp}`
      );
    } catch (err) {
      console.error("出错了:", err);
      return { data: null };
    }
  }
  // 清除
  async cleanRemoteItem(key, token) {}
  // 获取上传token
  async getUploadToken(key, body = {}) {
    let queryParameters = {};
    let url = this.conf.tokenUrl;
    let headers = this.conf.header;
    headers["Accept"] = "application/json";

    if (key !== undefined) {
      queryParameters["key"] = key;
    }

    let options = {
      method: "GET",
      url: url,
      params: queryParameters,
      data: body,
      headers: headers
    };

    const ret = await axios(options);
    return ret.data;
  }
  // 创建文件
  static createFile(key, content, type) {
    return new File([content], key, {
      type: contentType[type]
    });
  }
}

export default RemoteStorage;
